<?php

class SiteController extends Controller
{
	
	public function init() { }
	
	public function actions()
	{
		return array(
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	public function actionIndex()
	{
		$model=new Arquivo;
		$model->unsetAttributes();
		$pagina = 'buscar';
		if(isset($_POST['Arquivo']))
		{
			$model->attributes=$_POST['Arquivo'];
			$model->categoria=$_POST['Arquivo']['categoria'];
			$pagina = 'resultado';
		}
		$this->render($pagina, array(
			'model'=>$model,
		));
	}

	public function actionLogin()
	{
		$model=new LoginForm;
		$model->unsetAttributes();
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			if($model->validate() && $model->login()){
				$this->redirect(Yii::app()->user->returnUrl);
			}
		}
		$this->render('login',array('model'=>$model));
	}

	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	
	public function actionDownload($id)
	{
		$model = $this->loadModelUpload($id);
		$this->render('download',array(
			'model'=>$model,
		));
	}
	
	public function actionDownloadFile($id)
	{
		$model = $this->loadModelArquivo($id);
		$this->render('downloadFile', array('model'=>$model));
	}
	
	public function loadModelUpload($id)
	{
		$model=Upload::model()->findByPk($id);
		if($model===null || $model->excluido == 1)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	
	public function loadModelArquivo($id)
	{
		$model=Arquivo::model()->findByPk($id);
		if($model===null || $model->excluido == 1)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	
	public function actionDelete($id)
	{
		$this->loadModelArquivo($id)->deletar();
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}
	
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}
}